<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */

/**
 * Validation class for validating that a username is valid
 *
 * @category    RedCross
 * @package     RedCross_Validate
 */
class RedCross_Validate_Username extends Zend_Validate_Abstract
{
    /**
     * Validation failure message key for when the value is not a valid username
     * @var string
     */
    const NOT_USERNAME = 'notUsername';

    /**
     * Validation failure message key for when the value is an empty string
     * @var string
     */
    const STRING_EMPTY = 'stringEmpty';

    /**
     * Validation failure message template definitions
     * @var array
     */
    protected $_messageTemplates = array(
        self::NOT_USERNAME	=>	"'Dette er ikke et gyldig brukernavn",
        self::STRING_EMPTY	=>	"'Brukernavnet kan ikke være tomt"
    );

    /**
     * Whether to allow hyphens or not; on by default
     * @var boolean
     */
    private $_allowHyphens;

    /**
     * Sets default option values for this instance
     *
     * @param bool $allowHyphens
     * @return void
     */
    public function __construct($allowHyphens = true)
    {
        $this->_allowHyphens = (boolean) $allowHyphens;
    }

    /**
     * (non-PHPdoc)
     * @see library/Zend/Validate/Zend_Validate_Interface#isValid($value)
     */
    public function isValid($value)
    {
        $value = (string) $value;

        if (empty($value)) {
            $this->_error(self::STRING_EMPTY);
            return false;
        }

        $this->_setValue($value);

        $hyphens = $this->_allowHyphens ? '-_' : '';
        $pattern = '/[^\p{L}\p{N}' . $hyphens . ']/u';
        $match = preg_replace($pattern, '', $value);

        if ($value !== $match) {
            $this->_error(self::NOT_USERNAME);
            return false;
        }
        return true;
    }
}